/*
 * Copyright (C) 2018 xuexiangjys(xuexiangjys@163.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.xuexiang.xdlink.component.channel.impl.socket.server;

import com.xuexiang.xdlink.component.channel.IChannel;
import com.xuexiang.xdlink.component.channel.IDataReceiver;
import com.xuexiang.xdlink.component.channel.OnChannelListener;
import com.xuexiang.xdlink.component.channel.entity.ConnectStatusEnum;
import com.xuexiang.xdlink.component.channel.impl.AbstractDataReceiver;
import com.xuexiang.xdlink.exception.ChannelException;
import com.xuexiang.xdlink.logs.DCFLog;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 可建立多个socket长连接的服务
 *
 * @author xuexiang
 * @since 2018/9/6 下午5:32
 */
public class MultiServerSocketChannel extends AbstractServerSocketChannel {

    /**
     * 所有建立连接的socket
     */
    private List<Socket> mSockets = new ArrayList<>();

    /**
     * 对应的数据接收器
     */
    private List<IDataReceiver> mIDataReceivers = new ArrayList<>();

    /**
     * 构造函数
     *
     * @param port 服务开启的端口号
     */
    public MultiServerSocketChannel(int port) {
        super(port, true);
    }

    /**
     * 构造函数
     *
     * @param port               服务开启的端口号
     * @param isAutoSwitchThread 是否自动切换线程
     */
    public MultiServerSocketChannel(int port, boolean isAutoSwitchThread) {
        super(port, isAutoSwitchThread);
    }

    /**
     * 启动服务
     */
    @Override
    protected void startServer() {
        try {
            //只接收一个连接
            mServerSocket = new ServerSocket(mPort, 1);
            mServerSocket.setReuseAddress(true);
            handleConnectResult(true);

            waitConnect();
        } catch (Exception e) {
            e.printStackTrace();
            DCFLog.e("Socket[multi server] start failed!", e);
            handleConnectResult(false);
        }
    }

    /**
     * 等待客户端连接
     *
     * @throws IOException
     */
    private void waitConnect() throws IOException {
        while (isOpen()) {
            // 调用ServerSocket的accept()方法，等待下位机的连接
            Socket socket = mServerSocket.accept(); //这里是阻塞的方法
            socket.setTcpNoDelay(true);
            mSockets.add(socket);
            startAcceptData(new SocketDataReceiver(socket, getChannelListener()));
        }
    }

    @Override
    public boolean isOpen() {
        return super.isOpen() && mServerSocket != null && !mServerSocket.isClosed();
    }

    /**
     * 开始接收数据
     *
     * @param dataReceiver 数据接收器
     */
    @Override
    protected void startAcceptData(IDataReceiver dataReceiver) {
        if (dataReceiver != null) {
            mIDataReceivers.add(dataReceiver);
            dataReceiver.startWork();
        }
    }

    /**
     * 停止接收数据
     */
    @Override
    protected void stopAcceptData() {
        if (mIDataReceivers != null && mIDataReceivers.size() > 0) {
            for (int i = 0; i < mIDataReceivers.size(); i++) {
                mIDataReceivers.get(i).finishWork();
            }
            mIDataReceivers.clear();
        }
    }

    /**
     * 处理连接结果
     *
     * @param isConnectSuccess 是否连接成功
     */
    private void handleConnectResult(boolean isConnectSuccess) {
        if (isConnectSuccess) {
            DCFLog.i("Socket[multi server] start success...");

            updateConnectStatus(ConnectStatusEnum.CONNECT_SUCCESS);// 打开设备成功,发送命令
        } else {
            updateConnectStatus(ConnectStatusEnum.CONNECT_FAILED);
        }
    }

    @Override
    protected void writeBytes(byte[] message) throws ChannelException {
        if (mSockets != null && mSockets.size() > 0) {
            Iterator<Socket> it = mSockets.iterator();
            synchronized (it) {
                while (it.hasNext()) {
                    Socket socket = it.next();
                    try {
                        super.writeBytes(socket, message);
                    } catch (ChannelException e) {
                        e.printStackTrace();
                        it.remove();
                    }
                }
            }
        }
    }

    /**
     * Socket数据接收器
     *
     * @author xuexiang
     * @since 2018/8/24 上午11:00
     */
    protected class SocketDataReceiver extends AbstractDataReceiver {

        public SocketDataReceiver(Socket socket, OnChannelListener listener) {
            super(socket, listener);
        }

        @Override
        protected void onDataReceiveInterrupted(Exception e) {
            super.onDataReceiveInterrupted(e);
            removeSocket();
        }

        @Override
        public IChannel getChannel() {
            return MultiServerSocketChannel.this;
        }

        @Override
        protected void close() {
            removeSocket();
            super.close();
        }

        private void removeSocket() {
            if (mSockets != null) {
                mSockets.remove(getSocket());
            }
            if (mIDataReceivers != null) {
                mIDataReceivers.remove(this);
            }
        }
    }

}
